package com.fudan.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fudan.dto.entities.Question;
import com.fudan.dto.entities.Room;
import com.fudan.dto.entities.User;
import com.fudan.service.RoomServiceImpl;

@RestController
@RequestMapping("/room")
@CrossOrigin(origins = "http://localhost:4200")
public class RoomController {
	
	@Autowired
	private RoomServiceImpl roomService;
	
	@GetMapping("/getAllRooms")
	public List<Room> getAllRooms(){
		return roomService.getAllRooms();
	}
	

	@GetMapping("/getRoom")
	public Room getRoom(@RequestParam Integer roomId, @RequestParam Integer userId){
		//System.out.println(roomId);
		Room room = roomService.getRoom(roomId);
		return pupulateIsLikeField(room, userId);
	}
	
	
	private Room pupulateIsLikeField(Room room, Integer userId){
		if (room ==null){
			return null;
		}
		for (Question question :room.getQuestions()){
			if (question.getCreatedOwner().getUserId().equals(userId)){
				question.setLiked(true);
			}else{
				for (User user : question.getLikeUser()){
					if(userId.equals(user.getUserId())){
						question.setLiked(true);
					}
				}
			}	
		}	
		return room;
	}
	
	@RequestMapping(value="/createRoom",method = RequestMethod.POST)
    @ResponseBody
	public Room createRoom(String roomName, String userId){
		System.out.println(roomName + userId);
		return roomService.createRoom(roomName, userId);
	}
}
